/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.auth.interceptor;

import com.je.auth.AuthEngine;
import com.je.auth.check.exception.BackResultException;
import com.je.auth.check.exception.StopMatchException;
import com.je.auth.model.AuthRequestForServlet;
import com.je.auth.model.AuthResponseForServlet;
import com.je.auth.check.router.AuthRouteFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * sa-token基于路由的拦截式鉴权
 *
 * @author kong
 */
public class AuthRouteInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthEngine authEngine;

    /**
     * 每次进入拦截器的[执行函数]，默认为登录校验
     */
    public AuthRouteFunction function = (req, res, handler) -> authEngine.getAuthLoginManager().checkLogin();

    /**
     * 创建一个路由拦截器
     */
    public AuthRouteInterceptor() {
    }

    /**
     * 创建, 并指定[执行函数]
     *
     * @param function [执行函数]
     */
    public AuthRouteInterceptor(AuthRouteFunction function) {
        this.function = function;
    }

    /**
     * 静态方法快速构建一个
     *
     * @param function 自定义模式下的执行函数
     * @return sa路由拦截器
     */
    public static AuthRouteInterceptor newInstance(AuthRouteFunction function) {
        return new AuthRouteInterceptor(function);
    }

    // ----------------- 验证方法 -----------------

    /**
     * 每次请求之前触发的方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            function.run(new AuthRequestForServlet(request), new AuthResponseForServlet(response), handler);
        } catch (StopMatchException e) {
            // 停止匹配，进入Controller
        } catch (BackResultException e) {
            // 停止匹配，向前端输出结果
            if (response.getContentType() == null) {
                response.setContentType("text/plain; charset=utf-8");
            }
            response.getWriter().print(e.getMessage());
            return false;
        }

        // 通过验证
        return true;
    }

}
